# weibo_base.py
import os
import logging
from abc import ABC, abstractmethod
import sqlite3
import json

from dataclasses import asdict
from core.storage import UserStorage, WeiboStorage

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class WeiboBaseCrawler(ABC):
    def __init__(self, user_id, cookie, output_dir='./output'):
        self.user_id = user_id
        self.cookie = cookie
        self.output_dir = output_dir
        self.user_info = {}
        self.weibo_data = []

    @abstractmethod
    def _make_request(self,url):
        pass

    @abstractmethod
    def get_user_info(self):
        """获取用户基本信息"""
        pass

    @abstractmethod
    def get_weibo_data(self, start_page=1, max_pages=None):
        """获取用户微博数据"""
        pass

    def _parse_cookies(self, cookie_str):
        """将 Cookie 字符串转换为字典"""
        if not cookie_str:
            return {}
        cookies_dict = {}
        for item in cookie_str.split("; "):
            key, value = item.split("=", 1)
            cookies_dict[key] = value
        return cookies_dict

    @staticmethod
    def create_tables(db_path='data/weibo.db'):
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        # 创建 author 表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS author (
                user_id TEXT PRIMARY KEY,
                nickname TEXT,
                gender TEXT,
                location TEXT,
                birthday TEXT,
                description TEXT,
                verified_reason TEXT,
                weibo_count INTEGER,
                following_count INTEGER,
                follower_count INTEGER
            )
        ''')

        # 创建 weibo 表
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS weibo (
                id TEXT PRIMARY KEY,
                user_id TEXT,
                content TEXT,
                publish_time TEXT,
                device TEXT,
                repost_count INTEGER,
                comment_count INTEGER,
                like_count INTEGER,
                images TEXT,
                FOREIGN KEY (user_id) REFERENCES author(user_id)
            )
        ''')

        # 创建 comment 表（可选）
        # cursor.execute('''
        #     CREATE TABLE IF NOT EXISTS comment (
        #         id INTEGER PRIMARY KEY AUTOINCREMENT,
        #         weibo_id TEXT,
        #         user_id TEXT,
        #         content TEXT,
        #         publish_time TEXT,
        #         FOREIGN KEY (weibo_id) REFERENCES weibo(id),
        #         FOREIGN KEY (user_id) REFERENCES author(user_id)
        #     )
        # ''')

        conn.commit()
        conn.close()

    def save_weibo_data(self, db_path=None):
        db_path = db_path or self.db_path
        with sqlite3.connect(db_path) as conn:
            weibo_storage = WeiboStorage(conn)
            if isinstance(self.weibo_data[0], dict):
                weibos = self.weibo_data  # 直接使用字典列表
            else:
                weibos = [asdict(w) for w in self.weibo_data]  # 使用 dataclass 实例

            # weibos = [asdict(w) for w in self.weibo_data] # Weibo实例，不是词典
            new_count = weibo_storage.bulk_insert_weibos(weibos)
            logging.info(f"成功插入 {new_count} 条新微博")

    def save_user_info(self, db_path=None):
        db_path = db_path or self.db_path
        with sqlite3.connect(db_path) as conn:
            user_storage = UserStorage(conn)
            user_storage.save_user(self.user_info)
            logging.info("用户信息已保存到数据库")

    def save_to_sqlite(self, db_path=None):
        self.save_weibo_data(db_path)


    '''准备弃用方法'''

    def _save_results(self):
        """保存爬取结果到本地"""
        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)

        user_info_path = os.path.join(self.output_dir, f'{self.user_id}_user_info.json')
        with open(user_info_path, 'w', encoding='utf-8') as f:
            json.dump(self.user_info, f, ensure_ascii=False, indent=4)
        logging.info(f"用户信息已保存到 {user_info_path}")

        weibo_data_path = os.path.join(self.output_dir, f'{self.user_id}_weibo_data.json')
        with open(weibo_data_path, 'w', encoding='utf-8') as f:
            json.dump(self.weibo_data, f, ensure_ascii=False, indent=4)
        logging.info(f"微博数据已保存到 {weibo_data_path}")

    def _save_to_sqlite(self, db_path='weibo.db'):
        """将用户信息和微博数据保存到 SQLite 数据库"""
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()

        # 插入或更新 author 表
        author_data = (
            self.user_id,
            self.user_info.get('nickname'),
            self.user_info.get('gender'),
            self.user_info.get('location'),
            self.user_info.get('birthday'),
            self.user_info.get('description'),
            self.user_info.get('verified_reason'),
            self.user_info.get('weibo_count'),
            self.user_info.get('following_count'),
            self.user_info.get('follower_count')
        )
        cursor.execute('''
            INSERT OR IGNORE INTO author (
                user_id, nickname, gender, location, birthday, description, 
                verified_reason, weibo_count, following_count, follower_count
            ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
        ''', author_data)

        # 插入每条微博到 weibo 表
        for weibo in self.weibo_data:
            weibo_data = (
                weibo['id'],
                self.user_id,
                weibo['content'],
                weibo['publish_time'],
                weibo['device'],
                weibo['repost_count'],
                weibo['comment_count'],
                weibo['like_count'],
                json.dumps(weibo['images'], ensure_ascii=False)
            )
            cursor.execute('''
                INSERT OR IGNORE INTO weibo (
                    id, user_id, content, publish_time, device, 
                    repost_count, comment_count, like_count, images
                ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
            ''', weibo_data)

        conn.commit()
        conn.close()
        logging.info("数据已保存到 SQLite 数据库")
